<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import { useRouter } from 'vue-router'
import axios from 'axios'

// 类型定义
interface PostType {
  typeId: number
  typeName: string
}

// 数据响应式
const router = useRouter()
// 更新模块选项为减肥广场的模块
const postTypes = ref<PostType[]>([
  { typeId: 1, typeName: '健身教程' },
  { typeId: 2, typeName: '减肥经验' },
  { typeId: 3, typeName: '打卡日记' },
  { typeId: 4, typeName: '问答交流' },
  { typeId: 5, typeName: '饮食分享' }
])

const formData = reactive({
  typeId: 0,        // 选中的模块ID
  content: '',      // 帖子内容
  images: [] as string[]  // 图片URL列表
})

const maxContentLength = 500  // 最大内容字数
const maxImageCount = 9       // 最大图片数量

// 计算内容字数
const contentLength = computed(() => formData.content.length)

// 选择模块
const selectType = (typeId: number) => {
  formData.typeId = typeId
}

// 图片上传相关
const uploadImage = (event: Event) => {
  const input = event.target as HTMLInputElement
  const files = input.files

  if (!files || files.length === 0) return

  // 检查图片数量限制
  if (formData.images.length + files.length > maxImageCount) {
    showToast(`最多只能上传${maxImageCount}张图片`)
    return
  }

  // 模拟图片上传（实际项目中需要调用上传接口）
  for (let i = 0; i < files.length; i++) {
    const file = files[i]
    // 这里应该调用实际的上传接口，这里仅作演示
    const reader = new FileReader()
    reader.onload = (e) => {
      formData.images.push(e.target?.result as string)
    }
    reader.readAsDataURL(file)
  }

  // 清空input值，允许重复选择同一文件
  input.value = ''
}

// 移除图片
const removeImage = (index: number) => {
  formData.images.splice(index, 1)
}

// 发布帖子
const publishPost = async () => {
  // 验证必填项
  if (!formData.typeId) {
    showToast('请选择发布模块')
    return
  }

  if (!formData.content.trim()) {
    showToast('请输入内容')
    return
  }

  try {
    // 显示确认对话框
    await showConfirmDialog({
      title: '确认发布',
      message: '确定要发布这条帖子吗？',
    })

    // 调用发布接口（这里需要根据实际接口调整）
    const token = sessionStorage.getItem("token")
    const response = await axios.post('/api/post/add', {
      typeId: formData.typeId,
      content: formData.content,
      images: formData.images.join(',')
    }, {
      headers: {
        'token': token
      }
    })

    if (response.data.code === 200) {
      showToast('发布成功')
      // 返回上一页或跳转到广场页面
      router.back()
    } else {
      showToast(response.data.msg || '发布失败')
    }
  } catch (error) {
    showToast('网络错误')
    console.error(error)
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}
</script>

<template>
  <div class="post-container">
    <van-nav-bar
      title="发布帖子"
      left-text="取消"
      right-text="发布"
      left-arrow
      @click-left="goBack"
      @click-right="publishPost"
    />

    <div class="post-form">
      <!-- 选择模块 -->
      <div class="form-section">
        <div class="section-title">选择模块 *</div>
        <div class="type-selector">
          <van-tag
            v-for="type in postTypes"
            :key="type.typeId"
            :type="formData.typeId === type.typeId ? 'primary' : 'default'"
            size="medium"
            class="type-tag"
            @click="selectType(type.typeId)"
          >
            {{ type.typeName }}
          </van-tag>
        </div>
      </div>

      <!-- 内容输入 -->
      <div class="form-section">
        <div class="section-title">内容</div>
        <van-field
          v-model="formData.content"
          rows="4"
          autosize
          type="textarea"
          maxlength="500"
          placeholder="请输入内容..."
          show-word-limit
        />
      </div>

      <!-- 图片上传 -->
      <div class="form-section">
        <div class="section-title">图片 (最多9张)</div>
        <div class="image-uploader">
          <!-- 图片预览 -->
          <div
            v-for="(image, index) in formData.images"
            :key="index"
            class="image-preview"
          >
            <van-image
              :src="image"
              width="80"
              height="80"
              fit="cover"
              radius="4"
            />
            <van-icon
              name="cross"
              class="remove-icon"
              @click="removeImage(index)"
            />
          </div>

          <!-- 上传按钮 -->
          <div
            v-if="formData.images.length < maxImageCount"
            class="upload-button"
          >
            <input
              type="file"
              accept="image/*"
              multiple
              @change="uploadImage"
              class="file-input"
            />
            <van-icon name="plus" size="24" />
            <div class="upload-text">上传图片</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.post-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.post-form {
  padding: 16px;
}

.form-section {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 12px;
}

.type-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.type-tag {
  cursor: pointer;
}

.image-uploader {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-preview {
  position: relative;
}

.remove-icon {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #fff;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

.upload-button {
  width: 80px;
  height: 80px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
}

.file-input {
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.upload-text {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}
</style>